package com.xcesys.extras.remoting.security.impl;

import java.util.Collection;
import java.util.Date;

import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import com.xcesys.extras.core.exception.SystemException;
import com.xcesys.extras.core.security.service.AuthenticationService;
import com.xcesys.extras.remoting.BaseRemotingServiceImpl;
import com.xcesys.extras.remoting.security.RAuthenticationService;

@Service("RAuthenticationService")
@WebService(endpointInterface = "com.xcesys.extras.remoting.security.RAuthenticationService")
public class RAuthenticationServiceImpl extends BaseRemotingServiceImpl
		implements RAuthenticationService {
	@Autowired
	private AuthenticationService authService = null;

	@Override
	public void changePassword(String username, String oldPwd, String newPwd) {
		authService.changePassword(username, oldPwd, newPwd);
	}

	@Override
	public com.xcesys.extras.dataobject.security.Authentication doAuthenticate(
			String username, String password) {
		try {
			Authentication authentication = authService.doAuthenticate(
					username, password);
			Collection<? extends GrantedAuthority> grantedAuthorities = authentication
					.getAuthorities();

			String[] authorities = null;

			if (grantedAuthorities != null) {
				authorities = new String[grantedAuthorities.size()];
				int i = 0;
				for (GrantedAuthority authority : grantedAuthorities) {
					authorities[i] = authority.getAuthority();
					i++;
				}
			}
			com.xcesys.extras.dataobject.security.Authentication auth = new com.xcesys.extras.dataobject.security.Authentication();
			auth.setPrincipal(username);
			auth.setAuthenticated(true);
			auth.setAuthorities(authorities);
			auth.setDetails(authentication.getDetails());
			return auth;
		} catch (AuthenticationException e) {
			throw new SystemException(e.getLocalizedMessage());
		}
	}

	@Override
	public Date dummy() {
		return super.getSystemDate();
	}

	@Override
	public void logout(String username) {
		authService.logout(username);
	}
}
